﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Db.SysDb
{
    /// <summary>
    /// 用户
    /// </summary>
    [SugarTable("User")]
    public class User
    {
        [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
        public int Id { get; set; }
        /// <summary>
        /// 登录名
        /// </summary>
        public string LoginName { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }
        /// <summary>
        /// 分组
        /// </summary>
        [SugarColumn(ColumnName = "group", Length = 64, IsNullable = false, ColumnDescription = "分组", ColumnDataType = StaticConfig.CodeFirst_BigString)]
        public string Group { get; set; }
        /// <summary>
        /// 指纹
        /// </summary>
        [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
        public string Fingerprint { get; set; }
        /// <summary>
        /// 面容
        /// </summary>
        [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString)]
        public string Face { get; set; }
        /// <summary>
        /// 角色id（json）
        /// </summary>
        [SugarColumn(ColumnDataType = StaticConfig.CodeFirst_BigString, IsJson = true)]
        public List<int> RoleIds { get; set; } = new List<int>();
        /// <summary>
        /// 角色名称
        /// </summary>
        [SugarColumn(IsIgnore = true)]
        public List<string> RoleNames { get => (RoleIds == null || !RoleIds.Any()) ? new List<string>() : SysDbHelper.db.Queryable<Role>().Where(o => RoleIds.Contains(o.Id)).Select(o => o.Name).ToList(); }
        /// <summary>
        /// 是否最大权限
        /// </summary>
        public bool IsAdmin { get; set; }
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime Time { get; set; }
        /// <summary>
        /// 用户所属角色
        /// </summary>
        public List<Role> GetUserRoles()
        {
            if (RoleIds == null || !RoleIds.Any())
                return new List<Role>();
            if (IsAdmin)
                return SysDbHelper.db.Queryable<Role>().ToList();
            var ids = RoleIds.Select(o => Convert.ToInt32(o)).ToList();
            return SysDbHelper.db.Queryable<Role>().Where(o => ids.Contains(o.Id)).OrderBy(o => o.Id).ToList();
        }
    }
}
